package com.zhouqinuan.spring.cloud.develop.framework.demo.shardingsphere.jdbc.service;

import java.util.Date;

import org.apache.shardingsphere.api.hint.HintManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhouqinuan.spring.cloud.develop.framework.base.util.BeanUtil;
import com.zhouqinuan.spring.cloud.develop.framework.demo.shardingsphere.jdbc.mapper.UserInfoMapper;
import com.zhouqinuan.spring.cloud.develop.framework.demo.shardingsphere.jdbc.model.UserInfo;
import com.zhouqinuan.spring.cloud.develop.framework.demo.shardingsphere.jdbc.req.AddUserReq;
import com.zhouqinuan.spring.cloud.develop.framework.demo.shardingsphere.jdbc.req.GetUserInfoByIdReq;
import com.zhouqinuan.spring.cloud.develop.framework.demo.shardingsphere.jdbc.req.UpdateUserReq;
import com.zhouqinuan.spring.cloud.develop.framework.demo.shardingsphere.jdbc.resp.GetUserInfoByIdResp;

@Service
public class UserService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    public GetUserInfoByIdResp getUserInfoById(GetUserInfoByIdReq reqVO) {

        //强走主库，应对实时性要求高的场景
        HintManager hintManager = HintManager.getInstance();
        hintManager.setMasterRouteOnly();
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(reqVO.getUid());
        //清除分片键值，分片键值保存在ThreadLocal中，所以需要在操作结束时调用hintManager.close()来清除ThreadLocal中的内容。hintManager实现了AutoCloseable接口，可推荐使用try with resource自动关闭。
        hintManager.close();

        userInfo = userInfoMapper.selectByPrimaryKey(reqVO.getUid());

        return BeanUtil.mapToObject(userInfo, GetUserInfoByIdResp.class);
    }

    public int addUser(AddUserReq reqVO) {
        UserInfo userInfo = BeanUtil.mapToObject(reqVO, UserInfo.class);
        userInfo.setStatus(1);
        userInfo.setCreateTime(new Date());
        return userInfoMapper.insertSelective(userInfo);
    }

    public int updateUser(UpdateUserReq reqVO) {
        UserInfo userInfo = BeanUtil.mapToObject(reqVO, UserInfo.class);
        userInfo.setUpdateTime(new Date());
        return userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }
}
